import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import {indexOf} from 'lodash';
import {
  Card, Form, Input, Select, Button, Modal, message, Upload, notification, Tabs, Table, Popconfirm,
  DatePicker,  InputNumber, Tooltip, Alert, Icon, Row, Col,} from 'antd';

const TabPane = Tabs.TabPane;

import styles from './TableList.less';
import { isNull } from 'util';
import { convertProjectCode } from './components/toolkit';
import {tableChangePagination} from './components/Pagination'

import SignInfoForm from './components/SignInfoForm'

const FormItem = Form.Item;
const { Option } = Select;

@connect(({ zubie,baoming, loading }) => ({
  baoming,zubie,
  loading: loading.models.baoming,
}))
@Form.create()
export default class SignTable extends PureComponent {
  state = {
    modalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},
  };

  componentDidMount() {
    const { dispatch, location, baoming,zubieSignList } = this.props;
    const pathArray = location.pathname.split('/');
    const id = pathArray[3];
    this.setState({
      id,
    });
    dispatch({
      type: 'baoming/clean',
      payload: {},
    });
    dispatch({
      type: 'zubie/clean',
      payload: {},
    });
    dispatch({
      type: 'gameList/findById',
      payload: id,
      callback: () => {
        dispatch({
          type: 'zubie/queryAllZubieForGame',
          callback:()=>{
            const {zubie: { curZubie, zubieList }} = this.props;
            //console.log(curZubie)
            if(!curZubie){
              return
            }
            const zubieMap = zubieList.map( value =>{
              return value.code
            })
            if(indexOf(zubieMap, curZubie)>-1){
              this.onSelectZubie(curZubie);
            }else{
              this.props.dispatch({
                type: 'zubie/changeState',
                payload: {
                  curZubie: null,
                  curZubieObj: {},
                },
              });
            }
          }
        });
        
      },
    });

  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const params = tableChangePagination(pagination, filtersArg, sorter)
    this.setState({signPagination:JSON.parse(JSON.stringify(params))})
    params.zubieCode = this.props.zubie.curZubie,

    this.props.dispatch({
      type: 'baoming/querySignListForZubie',
      payload: params,
    });
  };

  showModifyModal = data => {

    this.setState({
      modalVisible: true,
      formhandle: this.handleModify,
      curSignInfo:data,
    });
  };

  handleModalVisible = (flag, datas) => {
    if(!this.props.zubie.curZubie){
      message.warn("请先选择组别")
      return
    }
    this.setState({
      modalVisible: !!flag,
      curSignInfo: null,
    });
    
  };

  handleModify = (fields) => {
    this.props.dispatch({
      type: 'baoming/modifySignInfo',
      payload: fields,
      callback: () => {
        this.handleModalVisible(false)
        message.success('报名修改成功');
      },
    });
  };

  signInfohandler = (values) => {
    if (values.id) {
      this.handleModify(values);
    } else {
      this.handleAdd(values);
    }
  }

  handleAdd = fields => {
    this.props.dispatch({
      type: 'baoming/addSignInfo',
      payload: fields,
      callback: () => {
        this.handleModalVisible(false)
        message.success('报名信息添加成功');
      },
    });
  };

  handlePrint = () => {
    window.print();
  };

  downloadTemplate = () => {
    if(this.props.zubie.curZubie)
      window.open('/bgms/gameInfo/downloadTemplate/' + this.props.zubie.curZubie, 'GET');
    else
      message.warn("请先选择组别")
  };

  clearSignInfo = () => {
    if(!this.props.zubie.curZubie){
      message.warn("请先选择组别")
      return
    }
    this.props.dispatch({
      type: 'baoming/clear',
      payload: this.props.zubie.curZubie,
      callback: () => {
        message.success('报名信息清除成功');
      },
    });
  }

  delete= (id) => {
    if(!this.props.zubie.curZubie){
      message.warn("请先选择组别")
      return
    }
    this.props.dispatch({
      type: 'baoming/delete',
      payload: {zubieCode:this.props.zubie.curZubie,
        signInfoId: id},
      callback: () => {
        message.success('报名信息删除成功');
      },
    });
  }

  signImport = value => {
    if (value.file.status === 'error') {
      notification.error({
        message: '错误',
        description: value.file.response ? value.file.response.msg:'上传的文件有问题',
      });
    } else if (value.file.status === 'done') {
      message.success('报名表导入成功');
      this.props.dispatch({
        type: 'baoming/querySignListForZubie',
        payload: {
          headers: {
            'x-page-num': 1,
            'x-page-size': 20
          },
          zubieCode: this.props.zubie.curZubie,
        },
      });
    }
  };

  onSelectZubie = value => {
    this.props.dispatch({
      type: 'zubie/changeState',
      payload: {
        curZubie: value,
      },
    });
    this.props.dispatch({
      type: 'zubie/queryZubieByCode',
      payload: value,
    });
    const params = {
      headers: {
        'x-page-num': 1,
        'x-page-size': 20
      },
      zubieCode: value,
    };
    this.props.dispatch({
      type: 'baoming/querySignListForZubie',
      payload:{
        zubieCode:value
      }
    });
  };

  handleSelectRows = (values) =>{
    this.setState({
      selectedRows: values,
    })
  }

  renderForm = () => {
    const { zubie: { curZubie, zubieList } } = this.props;
    return <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
    <Col md={6} sm={24}>
    <Select placeholder="请选择组别" style={{ width: '80%' }} value={curZubie} onChange={this.onSelectZubie}>
      {zubieList.map(element => { 
        if(element.enabled)
          return <Option key={'OP' + element.code} value={element.code}>
          {convertProjectCode(element.projectCode) + ' - ' + element.zubieName}
        </Option>
      })}
      </Select>
      </Col>
      {!curZubie && <Col md={6} sm={24} key='selectZubieMsg'>
          <FormItem>
            <Alert style={{flex:1}} message="请选择一个组别" type="error" icon={<Icon type="left" />} showIcon={true}/>
          </FormItem>
          </Col>}
      <Col style={{textAlign:'right'}} md={12} sm={24}>
        {this.renderButton()}
      </Col>
    </Row>
  }

  renderButton() {
    const { selectedRows } = this.state;
    const {curZubieObj} = this.props.zubie
    return <div className={styles.tableListOperator}>
      <Tooltip placement="topLeft" title="手动添加报名信息，组别开始编排后不能再添加" arrowPointAtCenter>
      <Button disabled={curZubieObj && curZubieObj.status !== 'NEW'} style={{ marginLeft: 8 }} onClick={()=>this.handleModalVisible(true)}>
            添加报名
      </Button>
      </Tooltip>
      <Popconfirm
        title="是否确定清除当前组别的报名数据，不能恢复，请确定？"
        onConfirm={this.clearSignInfo}
        okText="Yes"
        cancelText="No"
      >
        <Button disabled={curZubieObj && curZubieObj.status !== 'NEW'} style={{ marginLeft: 8 }}>清空报名表</Button>
      </Popconfirm>
      <Button disabled={curZubieObj && curZubieObj.status !== 'NEW'}
        type="primary"
        onClick={() => this.downloadTemplate()}
        style={{ marginLeft: 8 }}
      >
        下载报名模板
      </Button>
      
      <Upload
        action={`/bgms/gameInfo/upload/${this.props.zubie.curZubie}`}
        name="file"
        disabled={this.props.zubie.curZubie ? false : true}
        showUploadList={false}
        onChange={this.signImport}
      >
        <Tooltip placement="topLeft" title="导入新的报名表将会清空以前的报名信息" arrowPointAtCenter>
        <Button disabled={curZubieObj && curZubieObj.status !== 'NEW'} type="primary" style={{ marginLeft: 8 }} >
          导入报名表
        </Button>
        </Tooltip>
      </Upload>
      {selectedRows.length > 0 && <Button style={{ marginLeft: 8 }}>批量通过审查</Button>}
    </div>
  }

  parseIdcardDate = (value) => {
    if(value.length !== 18) {
      return "错误的身份证号"
    }else{
      const year = value.substring(6,10);
      const month = value.substring(10,12);
      //const day = value.substring(12,14);
      return moment(`${year}${month}`,'YYYYMM').fromNow().substring(0,3) + '岁';
    }
  }

  render() {
    const { baoming: { zubieSignList }, zubie:{curZubieObj}, loading } = this.props;
    const {modalVisible} = this.state;
    
    const singInfoMethod = {
      handleAdd: this.signInfohandler,
      handleModalVisible: this.handleModalVisible,
    };

    const columns = [
      {
        title: '序号',
        dataIndex: 'seq',
        width:100,
        sorter: true,
        width:100,
      },
      {
        title: '所属团队',
        dataIndex: 'team',
      },
      {
        title: '种子号',
        dataIndex: 'seedNo',
        width:100,
      },
      {
        title: '队内排名',
        dataIndex: 'teamNo',
        width:100,
      },
      {
        title: '运动员',
        width:240,
        key:"team1",
        id:1,
        children: [{
          title: '姓名',
          key:'yuadongyuan1',
          width:120,
          render: (value, row) =>
          row.athleteList && row.athleteList[0] && <span>{row.athleteList[0].userName}</span>
        },{
          title: '年龄',
          width:120,
          key:'yuadongyuanage1',
          render: (value, row) =>
          (row.athleteList && row.athleteList[0] && row.athleteList[0].idCard) && 
          <span>{this.parseIdcardDate(row.athleteList[0].idCard)}</span>
        }]
      },
      
    ];

    if(curZubieObj && ("WD" === curZubieObj.projectCode||"MD"=== curZubieObj.projectCode||"HD"=== curZubieObj.projectCode)){
      columns.push({
        title: '运动员',
        width:240,
        id:1,
        key:"team2",
        children: [{
          title: '姓名',
          width:120,
          key:'yuadongyuan2',
          render: (value, row) =>
          row.athleteList && row.athleteList[1] && <span>{row.athleteList[1].userName}</span>
        },{
          title: '年龄',
          width:120,
          key:'yuadongyuanage2',
          render: (value, row) =>
          (row.athleteList && row.athleteList[1] && row.athleteList[1].idCard) && 
          <span>{this.parseIdcardDate(row.athleteList[1].idCard)}</span>
        }]
      });
    }

    columns.push({
      title: '操作',
      width:150,
      render: (value, row) => (
        <Fragment key={`fragment${row.id}`} >
          <Tooltip placement="topLeft" title="比赛开始进行编排后不能再修改" arrowPointAtCenter>
            <Button disabled={curZubieObj && curZubieObj.status !== 'NEW'} key={`modifyBtn${row.id}`} onClick={()=>this.showModifyModal(row)}>修改</Button>
          </Tooltip>
          <Tooltip placement="topLeft" title="比赛开始进行编排后不能再删除" arrowPointAtCenter>
          <Popconfirm title="是否确定删除，不能恢复，请确定？" onConfirm={() => this.delete(row.id)} okText="Yes" cancelText="No">
            <Button disabled={curZubieObj && curZubieObj.status !== 'NEW'} key={`delete${row.id}`}>删除</Button>
          </Popconfirm>
          </Tooltip>
        </Fragment>
      ),
    });

    const parentMethods = {
      handleProcess: this.state.formhandle,
      handleModalVisible: this.handleModalVisible,
    };
    return (
      <Fragment>
        <Card>
          <div className={styles.tableList}>
          <div className={styles.tableListForm}>{this.renderForm()}</div>
          <Table
            loading={loading}
            bordered
            dataSource={zubieSignList.list}
            pagination={zubieSignList.pagination}
            columns={columns}
            onChange={this.handleStandardTableChange}
            size="small"
            />

          </div>
        </Card>

        <SignInfoForm
          {...singInfoMethod}
          modalVisible={modalVisible}
          curData={this.state.curSignInfo}
          projectCode= {curZubieObj && curZubieObj.projectCode}
          zubieCode={curZubieObj && curZubieObj.code}
        />
      </Fragment>
    );
  }
}
